package com.telecom.sxint.app.api.controller.UccpMessageController;

import cn.zjtele.pubinfo.common.http.request.RequestContextHolder;
import cn.zjtele.pubinfo.common.http.response.ResponseData;
import com.telecom.sxint.app.core.domain.entity.Messagepojo.App1UccpMessage;
import com.telecom.sxint.app.core.domain.entity.PubUser;
import com.telecom.sxint.app.core.domain.entity.Query.PageData;
import com.telecom.sxint.app.core.domain.entity.dto.MessageQueryDTO;
import com.telecom.sxint.app.core.service.Messageservice.IApp1UccpMessageService;
import io.swagger.v3.oas.annotations.Operation;
import org.apache.http.HttpResponse;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Comparator;
import java.util.List;

import cn.hutool.json.JSONObject;
import cn.zjtele.pubinfo.common.http.response.ResponseData;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.telecom.sxint.app.core.domain.entity.Messagepojo.App1UccpMessage;
import com.telecom.sxint.app.core.domain.entity.Messagepojo.App1UccpMessageParams;
import com.telecom.sxint.app.core.domain.entity.Vatinvoicepojo.App1Vatinvoinceprintlog;
import com.telecom.sxint.app.core.domain.entity.dto.MessageDTO;
import com.telecom.sxint.app.core.service.Messageservice.IApp1UccpMessageParamsService;
import com.telecom.sxint.app.core.service.Messageservice.IApp1UccpMessageService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.http.impl.client.HttpClients;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 
 * @since 2024-12-09
 */
@RestController
@RequestMapping("/app1-UccpMessage")
@Tag(name = "短信草稿控制器", description = "信息导出管理")
@RequiredArgsConstructor
public class App1UccpMessageController {
    @Autowired
    private IApp1UccpMessageService iApp1UccpMessageService;
    @Autowired
    private IApp1UccpMessageParamsService app1UccpMessageParamsService;
    /**
     * 查询全部
     */
    @Operation(summary = "查询所有短信草稿记录", description = "根据查询所有短信草稿记录")
    @GetMapping("/Messagelist")
    public ResponseData getList() {
        // 查询数据库，获取符合条件的记录
        List<App1UccpMessage> results = iApp1UccpMessageService.list();
        if (results==null||results.isEmpty()) {
            return ResponseData.failed("未查到相关记录","4001");
        }
        return ResponseData.success(results);
    }
    /**
     * 查询所有短信记录（分页）
     */
    @Operation(summary = "查询所有短信记录（分页）", description = "分页查询短信记录")
    @PostMapping("/getAllMessagesPage")
    public ResponseData<PageData<App1UccpMessage>> getAllMessagesPage(@RequestBody MessageQueryDTO messageQueryDTO) {
        // 查询所有短信记录（分页查询）
        PageData<App1UccpMessage> pageData = iApp1UccpMessageService.queryAllMessagesPage(messageQueryDTO);

        // 确保分页结果按发送时间排序
        // pageData.getRecords().sort(Comparator.comparing(App1UccpMessage::getSendTime).reversed());

        return ResponseData.success(pageData);
    }

    @Operation(summary = "查询所有短信记录", description = "获取所有短信记录")
    @GetMapping("/listAll")
    public ResponseData<List<App1UccpMessage>> listAll() {
        return iApp1UccpMessageService.listAll();
    }

    @Operation(summary = "根据手机号查询短信记录", description = "根据手机号查询短信记录")
    @GetMapping("/listByPhone/{phoneNumber}")
    public ResponseData<List<App1UccpMessage>> listByPhone(@PathVariable String phoneNumber) {
        return iApp1UccpMessageService.listByPhone(phoneNumber);
    }

    @Operation(summary = "根据ID查询短信记录", description = "根据短信记录ID查询")
    @GetMapping("/getById/{id}")
    public ResponseData<App1UccpMessage> getById(@PathVariable Integer id) {
        return iApp1UccpMessageService.getById(id);
    }

    @Operation(summary = "创建短信记录", description = "创建新的短信记录")
    @PostMapping("/create")
    public ResponseData<App1UccpMessage> create(@RequestBody App1UccpMessage message) {
        return iApp1UccpMessageService.create(message);
    }

    @Operation(summary = "修改短信记录", description = "修改现有的短信记录")
    @PutMapping("/update")
    public ResponseData<App1UccpMessage> update(@RequestBody App1UccpMessage message) {
        return iApp1UccpMessageService.update(message);
    }

    @Operation(summary = "删除短信记录", description = "根据ID删除短信记录")
    @DeleteMapping("/delete/{id}")
    public ResponseData delete(@PathVariable Integer id) {
        return iApp1UccpMessageService.delete(id);
    }
    /**
     * 查询所有短信记录（分页）
     */
    @Operation(summary = "查询所有短信记录（分页升序）", description = "分页查询短信记录")
    @PostMapping("/getAllMessagesPageAsc")
    public ResponseData<PageData<App1UccpMessage>> getAllMessagesPageAsc(@RequestBody MessageQueryDTO messageQueryDTO) {
        // 查询所有短信记录（分页查询）
        PageData<App1UccpMessage> pageData = iApp1UccpMessageService.queryAllMessagesPageAsc(messageQueryDTO);

        return ResponseData.success(pageData);
    }
    /**
     * 批量删除研究人员信息
     * @param ids
     * @return
     */
    @Operation(summary = "批量删除草稿", description = "根据ids删除草稿")
    @DeleteMapping("/UccpMessagedeleteids")
    public ResponseData deletByIds(@RequestBody List<Integer> ids) {
        if(ids==null||ids.isEmpty())return ResponseData.success("未选择删除记录");
        return ResponseData.success(iApp1UccpMessageService.deleteBatch(ids));
    }
    /**
     * 查询所有短信记录（分页）
     */
    @Operation(summary = "查询所有短信记录（分页倒序）", description = "分页查询短信记录")
    @PostMapping("/getAllMessagesPageDesc")
    public ResponseData<PageData<App1UccpMessage>> getAllMessagesPageDesc(@RequestBody MessageQueryDTO messageQueryDTO) {
        // 查询所有短信记录（分页查询）
        PageData<App1UccpMessage> pageData = iApp1UccpMessageService.queryAllMessagesPageDesc(messageQueryDTO);
        return ResponseData.success(pageData);
    }

    /**
     * 草稿短信批量发送
     * @param
     * @return
     */
    @Operation(summary = "草稿短信批量发送", description = "草稿短信批量发送")
    @PostMapping("/sendMoreMessage")
    public ResponseData sendMoreUccpMessage(HttpServletRequest request) throws UnsupportedEncodingException {
        String url = "http://134.108.13.13:8000/zjeop/rest/bssDomain/uccp/sendShortMessage";
        String responseString = "";
        // 创建连接池管理器
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        // 设置最大连接数
        connManager.setMaxTotal(100);
        // 设置每个路由的最大连接数
        connManager.setDefaultMaxPerRoute(20);
        String user = RequestContextHolder.getContext().getUserName()+"("+RequestContextHolder.getContext().getUserId()+")";
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(connManager)
                .build()) {
        List<App1UccpMessage> results = iApp1UccpMessageService.list(new QueryWrapper<App1UccpMessage>().eq("is_delete", 0));
        LocalDateTime now = LocalDateTime.now();
        for(App1UccpMessage result : results) {
            String jsonBody = "{"
                    + "\"accNbr\": \"" + result.getPhoneNumber()+ "\","
                    + "\"contentParam\": \"\","
                    + "\"extOrderId\": \"\","
                    + "\"orderContent\": \"" + result.getMessageContent() + "\","
                    + "\"password\": \"141024\","
                    + "\"requestTime\": \"" + now + "\","
                    + "\"sceneId\": \"7812\","
                    + "\"sendDate\": \"\","
                    + "\"lanId\": \"571\","
                    + "\"systemCode\": \"SXDXMP\","
                    + "\"transactionId\": \"SXDXMP202205050921580000024809\","
                    + "\"userAcct\": \"SXDXMP\","
                    + "\"state\": \"\","
                    + "\"sender\": \""+ user+"\""
                    + "}";
            HttpPost httpPost = new HttpPost(url);
            // 设置请求头
            httpPost.setHeader(new BasicHeader("X-APP-ID", "7932dcc94e4648823c0f364e4ec677e8"));
            httpPost.setHeader(new BasicHeader("X-APP-KEY", "b079aa0cb63f47431d576abc2d489908"));
            httpPost.setHeader(new BasicHeader("Content-Type", "application/json"));

            // 设置请求体
            StringEntity stringEntity = new StringEntity(jsonBody, "UTF-8");
            httpPost.setEntity(stringEntity);

            try {
                HttpResponse response = httpClient.execute(httpPost);
                // 将发送的信息插入数据库
                App1UccpMessageParams app1UccpMessageParams = JSON.parseObject(jsonBody, App1UccpMessageParams.class);
                // 原有端口返回信息
                String responseData = EntityUtils.toString(response.getEntity());
                JSONObject msg = new JSONObject(responseData);
                responseString += msg.getStr("msg") + "\n";
                if (responseData.contains("成功!消息接收成功，放入队列：uccp_order")) {
                    app1UccpMessageParams.setState("发送成功");
                    app1UccpMessageParamsService.save(app1UccpMessageParams);
                } else {
                    app1UccpMessageParams.setState("发送失败(" + msg.getStr("msg") + ")");
                    app1UccpMessageParamsService.save(app1UccpMessageParams);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseData.success(responseString);
    }

}
